from app.extensions import SessionLocal
from app.models.Clas import Clas
from app.models.Student import Student

class StudentRepository():
    def __init__(self, db: SessionLocal):
        self.db = db

    def get_by_keyword(self, keyword):
        """
        根据关键字查询数据
        :param keyword: 关键字
        :return: 如果查询成功返回数据，查询失败返回空列表
        """
        try:
            data = self.db.query(Student).filter(Student.name.like(f'%{keyword}%')).all()
            return data
        except:
            return []

    def delete_student(self, id):
        try:
            self.db.query(Student).filter(Student.id == id).delete()
            self.db.commit()
            return True
        except:
            return False

    def add_student(self, clas_id, name, gender):
        try:
            stu = Student(name=name, gender=gender, clas_id=clas_id)
            self.db.add(stu)
            self.db.commit()
            return True
        except Exception as e:
            print(e)
            return False

    def get_student_by_id(self, id):
        try:
            data = self.db.query(Student).filter(Student.id == id).one()
            return data
        except:
            return None

    def update_student(self, stu_id, new_name, new_gender, new_clas_id):
        try:
            stu = self.get_student_by_id(stu_id)
            stu.name = new_name if new_name != "" else stu.name
            stu.gender = new_gender if new_gender != "" else stu.gender
            stu.clas_id = int(new_clas_id) if new_clas_id != "" else stu.clas_id
            self.db.commit()
            return True
        except:
            return False